<?php


namespace app\home\controller;
use app\home\model\Admin as adminModel;
use think\Controller;
use think\Request;
use think\Validate;

class User extends Controller
{
    protected $adminModel;
    public function __construct(adminModel $adminModel)
    {
        parent::__construct();
        $this->adminModel = $adminModel;
    }

    public function user(){

    }

    public function password_show(){
        return $this->fetch();
    }

    public function password_reset(Request $request){
        $oldPassword = $request->param('oldPassword');
        $password = $request->param('password');
        $rePassword = $request->param('rePassword');
        $data = [
          'oldPassword'  => $oldPassword,
          'password'  => $password,
          'rePassword'  => $rePassword
        ];
        $message = [
            'password.different' => '新密码和旧密码不能一致'
        ];
        $validate = Validate::make([
            'oldPassword|原密码' => 'require',
            'password|新密码' => 'require|different:oldPassword',
            'rePassword|确认新密码' => 'require|confirm:password'
        ],$message);
        if (!$validate->check($data)) {
            return jsonRes([], $validate->getError(), 99);
        }
        $user_id = session('user_id');
        $info = $this->adminModel->where('id', $user_id)->find();
        if($info){
            if(md5($oldPassword) == $info['password']){
                $md5_password = md5($data['password']);
                $result = AdminModel::where('id', $user_id)->update(['password' => $md5_password]);
                if ($result) {
                    session('user_id', null);
                    return jsonRes('', '密码修改成功', 200);
                } else {
                    return jsonRes('', '密码修改失败', 99);
                }
            }else{
                return jsonRes([], '原密码输入错误！', 99);
            }
        }else{
            return jsonRes([], '用户不存在！', 99);
        }
    }
}